//I18N-IGNORE
package pay;


import JavaUtils.CSUtils.Log.CLog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {
    static final String tag = "TimeUtil";
    public static final long DAY = 24 * 3600 * 1000l;

    /**
     * @param args
     */
    public static void main(String[] args) {

//		int time = (int) (dateStrtoTimestamp("2020-06-03 00:00:00","yyyy-MM-dd HH:mm:ss")/1000);
//		boolean i = TimeUtil.isYesterday(time, 2);
//		System.out.println(i);
        System.err.print(getHours());

    }

    /**
     * 月初date
     */
    public static Date getFirstDayOfMonth(Date d) {
        return new Date(d.getYear(), d.getMonth(), 1);
    }

    /**
     * 向前（后）取某个月第一天
     */
    public static Date nextMonth(Date d, int offset) {
        int y = offset / 12;
        int m = offset % 12;
        return new Date(d.getYear() + y, d.getMonth() + m, 1);
    }

    /**
     * 取得时间字符串
     */
    public static String getDateString(Date d, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(d);
        } catch (Exception e) {
            return "";
        }
    }

    public static int getMonthOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    public static int getHour(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 判断2个日期是否同一天
     */
    public static boolean isSameDay(Date d1, Date d2) {
        if (d1 != null && d2 != null) {
            if (d1.getYear() == d2.getYear() && d1.getMonth() == d2.getMonth()
                    && d1.getDate() == d2.getDate()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获得月矩阵
     */
    public static int[][] getMonthMatrix(Date d) {
        Date f = getFirstDayOfMonth(d);
        Calendar c = Calendar.getInstance();
        c.setTime(f);
        int wd = c.get(Calendar.DAY_OF_WEEK);// 月初date在一周中的第几天
        int maxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);// 当月最大日期
        int fwc = 8 - wd;// 第一周天数//日是第一天，所以第一周只能到周六
        // int wc = (int) Math.ceil((double) (maxDay - fwc) / 7) + 1;// 周数
        int wc = ((maxDay + 6 - fwc) / 7) + 1;// 周数
        int[][] md = new int[wc][7];// 月方阵
        int start = 1;
        for (int i = 0; i < wc; i++) {
            for (int j = 0; j < 7; j++) {
                if (i * 7 + j + 1 > wd - 1) {//
                    md[i][j] = start;
                    start++;
                    if (start > maxDay) {
                        break;
                    }
                } else {
                    continue;
                }
            }
        }
        return md;
    }

    /**
     * 获得月数组，不用再计算几周，固定6周，靠前排列
     */
    public static int[] getMonthArray(Date d) {
        Date f = getFirstDayOfMonth(d);
        Calendar c = Calendar.getInstance();
        c.setTime(f);
        int wd = c.get(Calendar.DAY_OF_WEEK);// 月初date在一周中的第几天
        int maxDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);// 当月最大日期
        int[] md = new int[42];// 月数组
        int start = 1;
        for (int i = 0; i < md.length; i++) {
            if (i + 1 > wd - 1) {
                md[i] = start;
                start++;
                if (start > maxDay) {
                    break;
                }
            } else {
                continue;
            }
        }
        return md;
    }

    /**
     * 测试打印月矩阵
     */
    public static void printMonthMatrix(Date d, int value) {
        int[][] month = getMonthMatrix(d);
        StringBuilder sb = new StringBuilder();
        sb.append("SUN").append("\t");
        sb.append("MON").append("\t");
        sb.append("TUE").append("\t");
        sb.append("WED").append("\t");
        sb.append("THU").append("\t");
        sb.append("FRI").append("\t");
        sb.append("SAT").append("\n");

        for (int i = 0; i < month.length; i++) {
            for (int j = 0; j < 7; j++) {
                String s = String.valueOf(month[i][j] > 0 ? month[i][j] : "");
                if (month[i][j] > 0 && (value & (1 << (month[i][j] - 1))) != 0) {
                    s = s.concat("*");
                }
                if (i < 6) {
                    sb.append(s).append("\t");
                } else {
                    sb.append(s);
                }
            }
            sb.append("\n");
        }

        CLog.i(tag,sb.toString());
    }

    /**
     * 测试打印月数组，矩阵方式打印
     */
    public static void printMonthArray(Date d, int value) {
        int[] month = getMonthArray(d);
        StringBuilder sb = new StringBuilder();
        sb.append("SUN").append("\t");
        sb.append("MON").append("\t");
        sb.append("TUE").append("\t");
        sb.append("WED").append("\t");
        sb.append("THU").append("\t");
        sb.append("FRI").append("\t");
        sb.append("SAT").append("\n");

        for (int i = 0; i < month.length; i++) {
            String s = String.valueOf(month[i] > 0 ? month[i] : "");
            if (month[i] > 0 && (value & (1 << (month[i] - 1))) != 0) {
                s = s.concat("*");
            }
            if (i % 7 < 6) {
                sb.append(s).append("\t");
            } else {
                sb.append(s).append("\n");
            }
        }

        CLog.i(tag,sb.toString());
    }

    /**
     * 取得二进制中1的个数
     */
    public static int getBinaryCount1(int v) {
        if (v > 0) {
            int ret = 0;
            for (int i = 0; i < 32; i++) {
                if ((v & (1 << i)) != 0) {
                    ret++;
                }
            }
            return ret;
        }
        return 0;
    }

    /**
     * 获取当前系统秒
     *
     * @return
     */
    public static int getCurrentSecond() {
        return (int) (System.currentTimeMillis() / 1000l);
    }

    /**
     * 取得二进制中低位起第一个0的位次
     */
    public static int getMinZeroIndexOfBinary(int v) {
        for (int i = 0; i < 32; i++) {
            if ((v & (1 << i)) == 0) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 填充二进制中低位起第一个0的位置
     */
    public static int fillMinZeroOfBinary(int v) {
        int index = getMinZeroIndexOfBinary(v);
        if (index != -1) {
            return v | (1 << index);
        }
        return v;
    }



    public static boolean checkTime(int clientTime, int error) {
        return Math.abs(Player.getRealTime() - clientTime) <= error;
    }

    /**
     * 返回从当前时间到下一个基准时间的剩余时间（剩余时间，时、分、秒）
     */
    public static int[] getNextTimeArray(Date baseTime) {
        long time = new Date().getTime();
        time = baseTime.getTime() - time;
        time %= DAY;
        if (time < 0) {
            time += DAY;
        }
        int h = (int) (time / (3600 * 1000l));
        int m = (int) (time % ((3600 * 1000l)) / (60 * 1000l));
        int s = (int) (time % (60 * 1000l) / 1000);
        return new int[]{(int) (time / 1000), h, m, s};
    }

    /**
     * 将2018/01/01格式时间转换为时间戳
     */
    public static long dateStrtoTimestamp(String dateStr) {

        return dateStrtoTimestamp(dateStr, "yyyy/MM/dd HH:mm:ss");
    }

    public static long dateStrtoTimestamp(String dateStr, String formatStr) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        Date d = null;
        long timestamp = 0;
        try {
            d = format.parse(dateStr);
            timestamp = d.getTime();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return timestamp;
    }

    /**
     * 将2018-01-01格式时间转换为时间戳
     */
    public static long dateStrtoTimestamp2(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;
        long timestamp = 0;
        try {
            d = format.parse(dateStr);
            timestamp = d.getTime();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return timestamp;
    }

    public static String timestampToFormatDate(long timestamp, String format) {
        Date date = new Date(timestamp);
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 判断Timestamp∈[String startTime, String endTime)?true:false
     * 如果没有设置有效期，则为永久
     */
    public static boolean dateBetween(long ts, String st, String et) {
        st = st.trim();
        et = et.trim();
        if (st == null || et == null) return true;
        if (st.length() == 0 || et.length() == 0) return true;
        SimpleDateFormat format = null;
        if (st.indexOf("/") != -1) {
            format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        } else if (st.indexOf("-") != -1) {
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        } else {
            return false;
        }

        Date d = null;
        long startTime = 0;
        long endTime = 0;
        long timestamp = 0;
        boolean flag = true;
        try {
            startTime = format.parse(st).getTime();
            endTime = format.parse(et).getTime();
            if (startTime > endTime) {
                flag = false;
            }
            if (startTime > ts) {
                flag = false;
            }
            if (endTime < ts) {
                flag = false;
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 根据时间 获取当前时间
     */
    public static long getTodayFixByStr(String time) {
        String[] strs = time.split(":");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(strs[0]));
        cal.set(Calendar.MINUTE, Integer.valueOf(strs[1]));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis();
    }


    /**
     * 根据时间 获取该时间前n分钟的时间   格式 00:00
     */
    public static long getBeforeTwoHour(String time, int minusMinute) {
        String[] strs = time.split(":");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(strs[0]));
        cal.set(Calendar.MINUTE, Integer.valueOf(strs[1]));
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis() - minusMinute * 60 * 1000;

    }

    /**
     * 是否再时间内
     *
     * @param satrTime
     * @param endTime
     * @return
     */
    @SuppressWarnings("static-access")
    public static boolean isEffectuveDate(String satrTime, String endTime) {
        String[] satartimes = StringUtil.splitString(satrTime, '|');
        String starthour = satartimes[1];
        String[] starthours = starthour.split(":");
        Calendar statrcal = Calendar.getInstance();
        statrcal.add(statrcal.DATE, Integer.valueOf(satartimes[0]));
        statrcal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(starthours[0]));
        statrcal.set(Calendar.MINUTE, Integer.valueOf(starthours[1]));
        statrcal.set(Calendar.SECOND, 0);
        statrcal.set(Calendar.MILLISECOND, 0);
        String[] endtimes = StringUtil.splitString(endTime, '|');
        String endhour = endtimes[1];
        String[] endhours = endhour.split(":");
        Calendar endcal = Calendar.getInstance();
        endcal.add(endcal.DATE, Integer.valueOf(endtimes[0]));
        endcal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(endhours[0]));
        endcal.set(Calendar.MINUTE, Integer.valueOf(endhours[1]));
        endcal.set(Calendar.SECOND, 0);
        endcal.set(Calendar.MILLISECOND, 0);
        Calendar cal = Calendar.getInstance();
        Date date = new Date();
        cal.setTime(date);
        if (cal.after(statrcal) && cal.before(endcal)) {
            return true;
        }

        return false;
    }

    /**
     * 获取当前的月份
     *
     * @return
     */
    public static int getMonth() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前的年
     *
     * @return
     */
    public static int getYear() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    /**
     * 获取当前的月份
     *
     * @return
     */
    public static int getMonth(int time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time * 1000l);
        return cal.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前的周几,周一为第一天
     *
     * @return
     */
    public static int getWeekDay() {
        Calendar cal = Calendar.getInstance();
        int weekday = cal.get(Calendar.DAY_OF_WEEK);
        return weekday == 1 ? 7 : weekday - 1;
    }

    /**
     * 获取当前天
     *
     * @return
     */
    public static int getDay() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.DATE);
    }

    /**
     * 获取当前小时
     *
     * @return
     */
    public static int getHour() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取当前分钟
     *
     * @return
     */
    public static int getMinute() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.MINUTE);
    }

    /**
     * 获取当前秒
     *
     * @return
     */
    public static int getSecond() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.SECOND);
    }

    @SuppressWarnings("deprecation")
    public static int getHours() {
        Date data = new Date();
        data.getHours();
        if (data.getHours() == 0) {
            return 24;
        }
        return data.getHours();
    }

    /**
     * 是否是过去的的时间
     *
     * @param time
     * @return
     */
    public static boolean isYesterday(int time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time * 1000l);
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        return cal.get(Calendar.DAY_OF_YEAR) < c.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * 是否是过去的的时间  几天
     *
     * @param time
     * @return
     */
    public static boolean isYesterday(int time, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time * 1000l);
        cal.add(Calendar.DATE, day);
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        return cal.get(Calendar.DAY_OF_YEAR) <= c.get(Calendar.DAY_OF_YEAR);
    }


    public static int getDayFromServerStart(int startTimeSeconds) {
//		System.out.println("startTime:" + startTimeSeconds);
        //系统时间
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(startTimeSeconds * 1000l);
//		System.out.println(cal.getTime());
        //当前时间
        Calendar c = Calendar.getInstance();
//		System.out.println(c.getTime());
        System.out.println("startTime day:" + (c.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)));
        return c.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * 是否是 当前天
     *
     * @param time
     * @return
     */
    public static boolean isNowTime(int time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time * 1000l);
        Calendar c = Calendar.getInstance();
        Date date = new Date();
        c.setTime(date);
        return cal.get(Calendar.DAY_OF_YEAR) == c.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * 获取当前的月份的总天数
     *
     * @return
     */
    public static int getMonthDay() {
        Calendar cal = Calendar.getInstance();
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 时间转换
     *
     * @param date
     * @return
     */
    public static long getTime(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.getTimeInMillis();
    }

    public static String timestampToFormatDate(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }
}
